# coding=utf-8
import os
from utils import Common
from multiThreadings import MultiThreadings
from lxml import etree

class ExecRobot(object):
    def __init__(self):
        self.Comm = Common()
        self.cur_time = self.Comm.get_cur_time()
        self.threadings = MultiThreadings()
        self.param = {}

    # 调用robot执行测试用例
    def exec_robot(self):
        cmd_list = []
        self.param = self.Comm.get_param_from_jenkins()
        # 调试参数
        # self.param = {'testSuite': 'D:\\autotest\\重构工作流接口自动化测试_ERP352SP9_py3\\接口场景自动化用例', '--processes': '4', '--variable': 'remote_url:http://192.168.99.100:4444/wd/hub', '--outputdir': 'D:\\autotest\\重构工作流接口自动化测试_ERP352SP9_py3\\result\\10'}
        cmd = "robot "
        for k, v in self.param.items():
            # 先加入不含testSuite的命令，因为后面需要再拼接含.robot的所有命令
            if k != "testSuite":
                cmd = cmd + k + " " + v + " "

        # 如果不包含"-s","--suite","-t","--test" 这几种参数，需要改造参数
        if True not in list(map(lambda x: x in cmd, ["-s", "--suite", "-t", "--test"])):
            # 将所有.robot的路径文件，拼接成多个cmd命令文件，以便并发执行
            for file in self.Comm.get_robot_file(self.param):
                cmd_list.append(cmd + f" {file}")
            print(cmd_list)
        else:
            # 否则加上testSuite后就直接组成cmd参数
            cmd_list = [cmd + self.param["testSuite"]]

        try:
            self.threadings.multi(cmd_list)
        except Exception as e:
            print(f"Fail : {str(e)}")

    # 合并报告
    def exec_rebot(self):
        report_dir = ""
        try:
            try:
                report_dir = self.param["-d"]
            except KeyError:
                report_dir = self.param["--outputdir"]
        except KeyError:
            print("不存在-d或者--outputdir参数，无法合并报告！")
            exit(0)
        # cmd = r"rebot --output ./resultDir/output-{0}.xml -l ./resultDir/log-{0}.html -r ./resultDir/report-{0}.html --merge ./resultDir/result_{0}/output-*.xml".format(self.cur_time)
        # cmd = r'rebot -R -d "{0}\result\{1}"  -o "{0}\result\{1}\output.xml" "{0}\result\{1}\线程*\output.xml"&copy "{0}\result\{1}\线程*\*.png" "{0}\result\{1}"'.format(
        #     workspace, build_id)
        # cmd = rf'rebot -R -d "{report_dir}"  -o "{report_dir}\output.xml" "{report_dir}\线程*\output.xml"&copy "{report_dir}\线程*\*.png" "{report_dir}"'
        cmd = rf'rebot -R -d "{report_dir}"  -o "{report_dir}\output.xml" "{report_dir}\线程*\output.xml"&copy "{report_dir}\线程*\*.png" "{report_dir}"'
        print(cmd)
        os.system(cmd)
        # 读取合并后的output.xml文件，判断失败数量，并存入Jenkins环境变量中，后续bat文件进行判断是否继续执行失败用例
        xml = etree.parse(rf"{report_dir}\output.xml")
        fail_count = xml.xpath("//total/stat[text()='All Tests']/@fail")[0]
        print(f"run.py执行失败{fail_count}个用例!")
        # 通过txt记录失败个数
        with open(rf"{report_dir}\err.txt", "w") as f:
            f.write(fail_count)
        # 存入环境变量中，目前验证，能存入变量，但是bat脚本无法读取到
        os.environ["TESTFAIL"] = fail_count
        print(os.environ)

        # 删除硬盘中合并前的测试报告
        # 暂时先不删除调试下看看
        # self.Comm.clean_logs()

# ex = ExecRobot()
# ex.exec_robot()
